4  {ggplot2} and {gt} assembly



✓ All shared objects created successfully from _objects.R

When creating a series of outputs, it is desirable to keep them visually unified. Is it possible to combine plots and tables in a single figure? Yes, it is - including tables produced with the {gt} package. We will only need a small trick to convert a gt table to a grob, which we can then combine with a plot created with the famous {ggplot2} package.

  1. Make a plot Here, we will create a simple violin plot to visualize the distribution of measured δ13C across countries in this data set.
Show code
p_violin <- ggplot(dat_vegetation, aes(x = country_label, y = delta)) +
  geom_violin(colour = "black", fill = "#005C55FF") +
  theme_classic() +
  theme(
    plot.margin = margin(0, 0, 0, 0),
    plot.background = element_blank(),
    panel.background = element_blank(),
    axis.line.x = element_blank(),
    axis.line.y = element_line(colour = "black", linewidth = 0.75),
    axis.ticks.y = element_line(colour = "black", linewidth = 0.75),
    axis.ticks.x = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_text(colour = "black", size = 12),
    axis.title = element_blank(),
    aspect.ratio = 0.75
  )

  1. We will create a simple gt table
Show code
gt_for_plot <- dat_vegetation |>
  group_by(country) |>
  summarize(
    mean_d = mean(delta),
    median_d = median(delta)
  ) |>
  gt() |>
  tab_spanner(columns = contains("_d"), label = md("&delta;^13^C")) |>
  cols_label(
    country = "Country",
    mean_d = "Mean",
    median_d = "Median"
  ) |>
  # column labels and spanners in bold font face
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_column_labels(everything())
  ) |>
  tab_style(
    style = cell_text(weight = "bold"),
    locations = cells_column_spanners(spanners = everything())
  )
Country
δ13C
Mean Median
Argentina -27.61667 -27.45
Democratic Republic of the Congo -34.11429 -34.35
Kenya -19.80360 -23.30
Mongolia -25.28333 -24.75
  1. We need to convert the gt table to a grob (required by {patchwork}), which requires a few dependencies
Show code
library(magick)
library(ggplotify)

With a small function, we can first save the gt table as an PNG image and with help of the {ggplotify}, further conversion into a grob is possible:

Show code
as_grob_gt <- function(x) {
  tmp <- tempfile(fileext = ".png")
  gtsave(x, filename = tmp)
  img <- magick::image_read(tmp)
  
  # Returns a ggplot grob for patchwork
  return(ggplotify::as.grob(img)) 
}
  1. Assemble plot and table into a single figure

As mentioned above, we will use the {patchwork} package for a final plot-table assembly.

Show code
library(patchwork)

Once gt table is converted to a grob

Show code
gt_grob_patchwork <- as_grob_gt(gt_for_plot)

we can treat it as e.g., another ggplot2 figure and with help of {patchwork}’s syntax, control relative positions of plot and table as well as their alignment

Show code
p_violin / gt_grob_patchwork